package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.extend.WorkStatementTemplateModuleExtend;
import com.zb.mapper.ZjWorkStatementTemplateModuleMapper;
import com.zb.service.*;
import com.zb.vo.OrderStatementTemplateFieldVo;
import com.zb.vo.OrderStatementTemplateVo;
import com.zb.vo.TemplateModuleVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 工单结单模板模块关联表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-10-07
 */
@Service
public class ZjWorkStatementTemplateModuleServiceImpl extends ServiceImpl<ZjWorkStatementTemplateModuleMapper, ZjWorkStatementTemplateModule> implements ZjWorkStatementTemplateModuleService {
    @Resource
    private ZjWorkStatementTemplateModuleMapper workStatementTemplateModuleMapper;
    @Resource
    private ZjWorkModuleService workModuleService;
    @Resource
    private ZjWorkStatementTemplateService workStatementTemplateService;
    @Resource
    private ZjWorkStatementTemplateFieldService workStatementTemplateFieldService;
    @Resource
    private ZjWorkStatementTemplateFieldContentService workStatementTemplateFieldContentService;

    // 保存应用模块
    @Override
    public void save(Long custAccId, Long workStatementTemplateId, List<TemplateModuleVo> templateModuleIds, List<Long> delTemplateModuleIds) {
        if (null != delTemplateModuleIds && !delTemplateModuleIds.isEmpty()) {
            // todo 查询是否与工单结单表关联
//            QueryWrapper<ZjWorkStatementTemplateModule> wrapper = new QueryWrapper<>();
//            wrapper.select("module_id");
//            wrapper.in("id", delTemplateModuleIds);
//            List<Long> moduleIds = this.list(wrapper).stream().map(ZjWorkStatementTemplateModule::getModuleId).distinct().toList();
//
//            List<ZjWorkModule> modules = workModuleService.getPartInfoByIds(moduleIds);
//            Assert.isTrue(modules.isEmpty(), "应用模块[" + modules.stream().map(ZjWorkModule::getName).collect(Collectors.joining("、")) + "]已被使用中，不可删除");

            this.removeByIds(delTemplateModuleIds);
        }
        if (null == templateModuleIds || templateModuleIds.isEmpty()) {
            return;
        }
        List<ZjWorkStatementTemplateModule> adds = new ArrayList<>();
        List<ZjWorkStatementTemplateModule> updates = new ArrayList<>();
        ZjWorkStatementTemplateModule module = null;
        for (TemplateModuleVo vo : templateModuleIds) {
            module = new ZjWorkStatementTemplateModule();
            BeanUtil.copyProperties(vo, module);
            if (null != module.getId()) {
                updates.add(module);
                continue;
            }
            module.setId(IdWorker.getId());
            module.setCustAccId(custAccId);
            module.setWorkStatementTemplateId(workStatementTemplateId);
            adds.add(module);
        }
        if (!adds.isEmpty()) this.saveBatch(adds);
        if (!updates.isEmpty()) this.updateBatchById(updates);
    }


    // 保存工单模块结单模板
    @Override
    @Transactional
    public void saveOrderModuleFinishTemplate(Long custAccId, Long moduleId, List<Long> workStatementTemplateIds) {
        Assert.notEmpty(workStatementTemplateIds, "关联的结单模板不能为空，至少选项一项");
        QueryWrapper<ZjWorkStatementTemplateModule> wrapper = new QueryWrapper<>();
        wrapper.eq("module_id", moduleId);
        this.remove(wrapper);

        List<ZjWorkStatementTemplateModule> modules = new ArrayList<>();
        ZjWorkStatementTemplateModule templateModule = null;
        for (Long workStatementTemplateId : workStatementTemplateIds) {
            templateModule = new ZjWorkStatementTemplateModule();
            templateModule.setId(IdWorker.getId());
            templateModule.setCustAccId(custAccId);
            templateModule.setModuleId(moduleId);
            templateModule.setWorkStatementTemplateId(workStatementTemplateId);
            modules.add(templateModule);
        }
        this.saveBatch(modules);
    }

    // 根据结单模板ID获取应用模块
    @Override
    public List<WorkStatementTemplateModuleExtend> getModuleByWorkStatementTemplateIds(List<Long> workStatementTemplateIds) {
        if (null == workStatementTemplateIds || workStatementTemplateIds.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkStatementTemplateModule> wrapper = new QueryWrapper<>();
        wrapper.select("id", "work_statement_template_id", "module_id");
        wrapper.in("work_statement_template_id", workStatementTemplateIds);
        List<ZjWorkStatementTemplateModule> templateModules = this.list(wrapper);
        List<Long> moduleIds = templateModules.stream().map(ZjWorkStatementTemplateModule::getModuleId).distinct().toList();

        List<ZjWorkModule> workModules = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(moduleIds)) {
            QueryWrapper<ZjWorkModule> moduleQueryWrapper = new QueryWrapper<>();
            moduleQueryWrapper.select("id", "name");
            moduleQueryWrapper.in("id", moduleIds);
            workModules.addAll(workModuleService.list(moduleQueryWrapper));
        }

        return templateModules.stream().map(m -> {
            WorkStatementTemplateModuleExtend tem = new WorkStatementTemplateModuleExtend();
            BeanUtil.copyProperties(m, tem);
            tem.setName(workModules.stream().filter(f -> Objects.equals(f.getId(), m.getModuleId())).map(ZjWorkModule::getName).findFirst().orElse(""));
            return tem;
        }).toList();
    }

    // 根据结单模板ID获取应用模块
    @Override
    public List<ZjWorkStatementTemplateModule> getModuleByWorkStatementTemplateId(Long workStatementTemplateId) {
        QueryWrapper<ZjWorkStatementTemplateModule> wrapper = new QueryWrapper<>();
        wrapper.select("id", "work_statement_template_id", "module_id");
        wrapper.eq("work_statement_template_id", workStatementTemplateId);
        return this.list(wrapper);
    }

    // 根据结单模板ID删除
    @Override
    public void deleteBatchByWorkStatementTemplateIds(List<Long> workStatementTemplateIds) {
        if (null == workStatementTemplateIds || workStatementTemplateIds.isEmpty()) {
            return;
        }
        QueryWrapper<ZjWorkStatementTemplateModule> wrapper = new QueryWrapper<>();
        wrapper.in("work_statement_template_id", workStatementTemplateIds);
        this.remove(wrapper);
    }

    // 根据工单模块ID获取结单模板的应用模块
    @Override
    public List<ZjWorkStatementTemplateModule> getByModuleId(Long moduelId) {
        QueryWrapper<ZjWorkStatementTemplateModule> wrapper = new QueryWrapper<>();
        wrapper.select("id", "work_statement_template_id", "module_id");
        wrapper.eq("module_id", moduelId);
        return this.list(wrapper);
    }

    // 根据工单模块ID集合查询关联结单模板应用模块
    @Override
    public List<ZjWorkStatementTemplateModule> getByModuleIds(List<Long> moduleIds) {
        if (null == moduleIds || moduleIds.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkStatementTemplateModule> wrapper = new QueryWrapper<>();
        wrapper.select("id", "work_statement_template_id", "module_id");
        wrapper.in("module_id", moduleIds);
        return this.list(wrapper);
    }

    // 根据模块ID获取结单模板及结单字段
    @Override
    public List<OrderStatementTemplateVo> getFinishOrderTemplateFieldByModuleId(Long moduleId) {
        QueryWrapper<ZjWorkStatementTemplateModule> wrapper = new QueryWrapper<>();
        wrapper.select("work_statement_template_id");
        wrapper.eq("module_id", moduleId);
        List<ZjWorkStatementTemplateModule> templateModuleList = this.list(wrapper);
        if (CollectionUtil.isEmpty(templateModuleList)) {
            return new ArrayList<>();
        }
        List<Long> workStatementTemplateIds = templateModuleList.stream().map(ZjWorkStatementTemplateModule::getWorkStatementTemplateId).distinct().toList();

        QueryWrapper<ZjWorkStatementTemplateField> fieldQueryWrapper = new QueryWrapper<>();
        fieldQueryWrapper.select("id", "work_statement_template_id", "name", "type", "upload_size", "upload_qty", "tip", "is_required AS required");
        fieldQueryWrapper.in("work_statement_template_id", workStatementTemplateIds).eq("is_disabled", false);
        fieldQueryWrapper.orderByDesc("is_required", "gmt_update");
        List<ZjWorkStatementTemplateField> templateFieldList = workStatementTemplateFieldService.list(fieldQueryWrapper);
        if (CollectionUtil.isEmpty(templateFieldList)) {
            return new ArrayList<>();
        }
        List<ZjWorkStatementTemplateFieldContent> fieldContentList = workStatementTemplateFieldContentService.getByWorkStatementTemplateFieldIds(templateFieldList.stream().map(ZjWorkStatementTemplateField::getId).toList());

        QueryWrapper<ZjWorkStatementTemplate> workStatementTemplateQueryWrapper = new QueryWrapper<>();
        workStatementTemplateQueryWrapper.select("id", "name");
        workStatementTemplateQueryWrapper.eq("is_disabled", false)
                .in("id", workStatementTemplateIds);
        List<ZjWorkStatementTemplate> statementTemplateList = workStatementTemplateService.list(workStatementTemplateQueryWrapper);
        return statementTemplateList.stream().map(tem -> {
            OrderStatementTemplateVo vo = new OrderStatementTemplateVo();
            vo.setId(tem.getId());
            vo.setName(tem.getName());
            vo.setTemplateFieldVos(templateFieldList.stream().filter(f -> Objects.equals(f.getWorkStatementTemplateId(), tem.getId())).map(templateField -> {
                OrderStatementTemplateFieldVo fieldVo = new OrderStatementTemplateFieldVo();
                BeanUtil.copyProperties(templateField, fieldVo);
                fieldVo.setContent(fieldContentList.stream().filter(f -> Objects.equals(f.getWorkStatementTemplateFieldId(), templateField.getId())).map(ZjWorkStatementTemplateFieldContent::getVal).toList());
                return fieldVo;
            }).toList());
            return vo;
        }).toList();
    }

    // 根据模块ID获取结单模板
    @Override
    public List<Long> getWorkStatementTemplateModuleByModuleId(Long moduleId) {
        QueryWrapper<ZjWorkStatementTemplateModule> wrapper = new QueryWrapper<>();
        wrapper.select("work_statement_template_id")
                .eq("module_id", moduleId);
        return this.list(wrapper).stream().map(ZjWorkStatementTemplateModule::getWorkStatementTemplateId).toList();
    }

}
